package cn.gov.cus.rmftquartz.common.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 封装ThreadLocal对象的工具类
 * @author wxming.
 * @date 2018/3/13.
 */
public class ThreadLocalUtil {
    private static ThreadLocalUtil localUtil = new ThreadLocalUtil();
    private Map<String,ThreadLocal>  localMap;

    private ThreadLocalUtil(){
        localMap = new ConcurrentHashMap<>(16);//线程安全的map。
    }

    public static ThreadLocalUtil getInstance(){//单例模式
        return localUtil;
    }

    public <T> void set(String key,T value){
        ThreadLocal<T> threadLocal = new ThreadLocal<>();
        threadLocal.set(value);
        localMap.put(key + Thread.currentThread().hashCode(),threadLocal);
    }

    public Object get(String key){
        return localMap.get(key + Thread.currentThread().hashCode()).get();
    }

    public void remove(String key){
        localMap.get(key + Thread.currentThread().hashCode()).remove();
    }
}
